import React, { useEffect, useState } from 'react';
import { Form, Input, Button, Tabs, message, Checkbox } from 'antd';
import { login, register } from '../../service/concept-service'
import { useNavigate } from 'react-router-dom'; // For React Router v6
import useUserStore from '../../store/userStore'; // Import the user store


const { TabPane } = Tabs;

const Login = () => {
  const [activeTab, setActiveTab] = useState('login');
  const navigate = useNavigate(); // Initialize navigate for navigation
  const [form] = Form.useForm();
  const setUser = useUserStore((state) => state.setUser);
  useEffect(() => {
    // 从 localStorage 中获取存储的邮箱和密码
    const savedEmail = localStorage.getItem('savedEmail');
    const savedPassword = localStorage.getItem('savedPassword');
    const remember = localStorage.getItem('remember') === 'true';

    if (remember) {
      form.setFieldsValue({
        email: savedEmail,
        password: savedPassword,
        remember,
      });
    }
  }, [form]);


  const onFinish = (values) => {
    console.log('Success:', values);
    const { email = '', password = '', remember = '' } = values;
    if (activeTab === 'login') {
      if (remember) {
        // 将邮箱和密码存储到 localStorage
        localStorage.setItem('savedEmail', email);
        localStorage.setItem('savedPassword', password);
        localStorage.setItem('remember', true);
      } else {
        // 清除存储的邮箱和密码
        localStorage.removeItem('savedEmail');
        localStorage.removeItem('savedPassword');
        localStorage.setItem('remember', false);
      }
      login({
        email,
        password
      }).then(res => {
        const { success, data={} } = res;
        message.success('登录成功');
        setUser({ id: data.id, email: data.email }); // Update the user store
        navigate('/concept'); // Navigate to concept page
      }).catch(err => {
        message.error(err.errorMsg || '登录失败');
      });
    }
    if (activeTab === 'register') {
      register({
        email,
        password
      }).then(res => {
        message.success('注册成功');
        // 切换到登录
        setActiveTab('login');
      }).catch(err => {
        message.error(err.errorMsg || '注册失败');
      });
    }
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <div
      style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
        backgroundColor: '#333',
        // backgroundImage: 'url(/path/to/your/background.jpg)',
        backgroundSize: 'cover',
      }}
    >
      <div style={{ width: 350, maxWidth: 500, padding: '50px', backgroundColor: 'rgba(255, 255, 255, 0.8)', borderRadius: '8px' }}>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="登录" key="login">
            <Form
              form={form}
              name="login"
              initialValues={{ remember: true }}
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
            >
              <Form.Item
                name="email"
                rules={[
                  { required: true, message: '请输入邮箱!' },
                  { type: 'email', message: '请输入有效的邮箱!' },
                ]}
              >
                <Input placeholder="邮箱" />
              </Form.Item>

              <Form.Item
                name="password"
                rules={[{ required: true, message: '请输入密码!' }]}
              >
                <Input.Password placeholder="密码" />
              </Form.Item>
              <Form.Item name="remember" valuePropName="checked">
                <Checkbox>记住我</Checkbox>
              </Form.Item>
              <Form.Item>
                <Button type="primary" htmlType="submit" block>
                  登录
                </Button>
              </Form.Item>
            </Form>
          </TabPane>
          <TabPane tab="注册" key="register">
            <Form
              name="register"
              initialValues={{ remember: true }}
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
            >
              <Form.Item
                name="email"
                rules={[
                  { required: true, message: '请输入邮箱!' },
                  { type: 'email', message: '请输入有效的邮箱!' },
                ]}
              >
                <Input placeholder="邮箱" />
              </Form.Item>

              <Form.Item
                name="password"
                rules={[{ required: true, message: '请输入密码!' }]}
              >
                <Input.Password placeholder="密码" />
              </Form.Item>

              <Form.Item>
                <Button type="primary" htmlType="submit" block>
                  注册
                </Button>
              </Form.Item>
            </Form>
          </TabPane>
        </Tabs>
      </div>
    </div>
  );
};

export default Login;